"use strict";
const path = require("path");
const fs = require("fs");
const Command = require("@unluna/command");
const log = require("@unluna/log");
const inquirer = require("inquirer");
const semver = require("semver");
const fse = require("fs-extra");
const TYPE_PROJECT = "TYPE_PROJECT";
const TYPE_COMPONENT = "TYPE_COMPONENT";

class InitCommand extends Command {
	init() {
		this.projectName = this._args[0] || "";
		this.force = !!this._args[1].force;
		log.verbose("projectName", this.projectName);
		log.verbose("force", this.force);
	}

	async exec() {
		try {
			// 1. 准备阶段
			const info = await this.prepare();
			console.log("info", info);
			// 2. 下载模板

			// 3. 安装模板
		} catch (e) {
			log.error(e.message);
			process.exit(1);
		}
	}

	async prepare() {
		// const localPath2 = path.resolve('.');
		const localPath = process.cwd();
		// 1. 判断目录是否为空
		if (!this.isDirEmpty(localPath)) {
			let isContinue = false;
			if (!this.force) {
				isContinue = await inquirer.prompt([{
					type: "confirm",
					message: "当前文件夹不为空，您是否要执行覆盖操作?",
					name: "isContinue"
				}]).isContinue;
			}
			// 二次确认
			if (isContinue || this.force) {
				// 覆盖操作
				const {isDel} = await inquirer.prompt([{
					type: "confirm",
					message: "即将删除当前所有文件，确定要继续么?",
					name: "isDel"
				}]);
				if (isDel) {
					// 清空文件，但是不会删除文件夹
					fse.emptyDirSync(localPath);
				}
			} else {
				return;
			}
		}
		return this.getProjectInfo();
	}

	async getProjectInfo() {
		const that = this;
		let projectInfo = {};
		const options = [
			{
				type: "input",
				message: "请输入项目名",
				name: "projectName",
				default: "my-project",
				validate(input) {
					const done = this.async();
					that.validateProjectName(input)
						.then((isValid) => {
							if (isValid) {
								done(null, true);
							} else {
								done("项目名首位必须为英文，不能输入特殊字符且不能以下划线中划线结尾！");
							}
						})
						.catch(err => {
							done("项目名称校验出错: " + err.message);
						});
				},
			},
			{
				type: "input",
				message: "项目版本号",
				name: "version",
				default: "0.0.1",
				validate(input) {
					const done = this.async();
					if (!!semver.valid(input)) {
						done(null, true);
					} else {
						done("请输入合法的版本号");
					}
				},
				filter: (input) => {
					if (!!semver.valid(input)) {
						return semver.valid(input);
					} else {
						return input;
					}
				}
			},
		];
		const {dirType} = await inquirer.prompt([
			{
				type: "list",
				message: "请选择你要创建的类型",
				name: "dirType",
				default: TYPE_PROJECT,
				choices: [
					{
						value: TYPE_PROJECT,
						name: "项目",
					},
					{
						value: TYPE_COMPONENT,
						name: "组件",
					}
				]
			}
		]);

		switch (dirType) {
			case TYPE_COMPONENT: {
				break;
			}
			case TYPE_PROJECT: {
				const {projectName, version} = await inquirer.prompt(options);
				projectInfo = {
					dirType,
					projectName,
					version
				};
				break;
			}
		}

		return projectInfo;
	}

	async validateProjectName(input) {
		await new Promise(resolve => setTimeout(resolve, 100));
		return /^[a-zA-Z]+(-[a-zA-z][a-zA-Z0-9]*|_[a-zA-z][a-zA-Z0-9]]*|[a-zA-Z0-9])$/.test(input);
	}

	isDirEmpty(localPath) {
		const fileList = fs.readdirSync(localPath)
			.filter(file => !file.startsWith(".") && !["node_modules"].includes(file));
		return !fileList.length;
	}
}

const factory = (...args) => new InitCommand(...args);

module.exports = factory;
module.exports.InitCommand = InitCommand;

